import requests
import json
from PIL import Image
import io
import base64
import os
def print_png_files(directory):
    """
    打印目录下所有.png文件的完整路径
    
    参数:
        directory (str): 要搜索的目录路径
    """
    print(f"在目录 {directory} 中找到的PNG文件:")
    count = 0
    
    # 遍历目录树
    for root, dirs, files in os.walk(directory):
        for file in files:
            # 检查文件是否以.png结尾（不区分大小写）
            if file.lower().endswith('.jpg'):
                # 拼接完整路径
                full_path = os.path.join(root, file)
                print(full_path)
           #  调用API服务器解析数据生成JOSN文件  
                call_detect_api(full_path)
                count += 1
    
    print(f"\n共找到 {count} 个PNG文件")

def call_detect_api(image_path):
    """
    调用AI检测API并将返回的JSON结果保存到文件
    
    参数:
        image_path (str): 图片文件的完整路径
    
    返回:
        dict: API返回的JSON数据，如果出错返回None
    """
    try:
        # 打开图片并转换为JPEG格式的Base64编码
        with Image.open(image_path) as img:
            buffered = io.BytesIO()
            img.convert('RGB').save(buffered, format='JPEG')  # 确保转换为RGB模式
            base64_encoded = base64.b64encode(buffered.getvalue()).decode('utf-8')
        
        # 构造请求负载
        payload = {"image": {"file": base64_encoded}}
        url = "http://175.168.20.7:3154/x-api/v1/ai/detect/all"
        headers = {"Content-Type": "application/json"}
        
        # 发送POST请求
        response = requests.post(
            url, 
            headers=headers, 
            data=json.dumps(payload),
            timeout=10  # 添加超时设置
        )
        
        # 检查HTTP状态码
        response.raise_for_status()
        
        # 解析JSON响应
        result_json = response.json()
        
        # 生成输出文件路径（与图片相同目录，相同文件名，后缀改为.json）
        directory = os.path.dirname(image_path)
        filename = os.path.splitext(os.path.basename(image_path))[0] + '.json'
        output_path = os.path.join(directory, filename)
        
        # 将JSON结果写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(result_json, f, indent=2, ensure_ascii=False)
        
        print(f"API结果已保存到: {output_path}")
        return result_json
        
    except Exception as e:
        print(f"处理图片时出错: {image_path}")
        print(f"错误详情: {str(e)}")
        return None
# 使用示例
if __name__ == "__main__":
    # 替换为你的实际图片路径
    image_path = "./pic"
    print_png_files(image_path)    
    # 调用API并保存结果
    #api_response = call_detect_api(image_path)
    
    # 如果需要进一步处理结果，可以使用api_response变量

